package Service;

import DAO.BookDAO;
import DAO.CommentDAO;
import DAO.UserDAO;
import DATA.Book;
import DATA.Comment;
import DATA.User;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.IOException;
import java.sql.SQLException;
import java.util.*;

@WebServlet(name = "getBook", value = "/getBook")
public class getBook extends HttpServlet {
//接受从booklist传过来的
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String bookName = req.getParameter("bookName");
        try {
            List<Book> books = BookDAO.FindbyName(bookName);
            Book book = books.get(0);//暂时先取第一个
            req.setAttribute("bookName", book.getBookName());
            req.setAttribute("bookType", book.getBookType());
            req.setAttribute("author", book.getAuthor());
            req.setAttribute("recommend",book.getRecommend());
            req.setAttribute("bid", book.getId());
            try {
                List<Comment> comments=CommentDAO.findByBookID(book.getId());
                Iterator<Comment> commentsIterator = comments.listIterator();
                ArrayList<muchInfo> commentsList = new ArrayList();//就为了三个数，我要手动建了一个新类来传

                while (commentsIterator.hasNext()) {
                    Comment aComment = commentsIterator.next();
//                    ArrayList aCommentInfo = new ArrayList();//用一个列表存进用户名、评论和点赞
                    commentsList.add(new muchInfo(new UserDAO().FindbyId(aComment.getuId()).getUsername(),aComment.getContent(),aComment.getWhich()));
//
                }
                req.setAttribute("comments", commentsList);

                req.getRequestDispatcher("BookDetail.jsp").forward(req, resp);

            } catch (SQLException e) {
                throw new RuntimeException(" 找评论失败");
            }

        } catch (SQLException e) {
            throw new RuntimeException("找书失败");
        }


    }
}


